﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using FikriKibar.Business.Abstract;
using FikriKibar.Common.Entities;
using FikriKibar.Common.Exceptions;
using FikriKibar.Common.Helpers;
using FikriKibar.Common.Validation.FluentValidation.Keyword;
using FikriKibar.DataAccess;
using FikriKibar.DataAccess.Abstract;
using FikriKibar.Entities.Abstract;
using FikriKibar.Entities.Composite.BaseModels;
using FikriKibar.Entities.Concrete;
using FikriKibar.Globalization;

namespace FikriKibar.Business.Concrete
{
    public class KeywordManager : IKeywordService
    {
        #region Global Declarations

        private readonly IKeywordDal _keywordDal = new EfKeywordDal();

        private readonly IKeywordLanguageLineDal _keywordLanguageLineDal = new EfKeywordLanguageLineDal();

        private readonly IKeywordLanguageLineHistoryDal _keywordLanguageLineHistoryDal = new EfKeywordLanguageLineHistoryDal();

        private readonly IKeywordHistoryDal _keywordHistoryDal = new EfKeywordHistoryDal();

        private readonly ILanguageDal _languageDal = new EfLanguageDal();

        private readonly ISettingDal _settingDal = new EfSettingDal();
        #endregion
        #region Methods
        public AddModel<KeywordLanguageLine> Add()
        {
            return new AddModel<KeywordLanguageLine>
            {
                LanguageList = _languageDal.Filter(e => e.IsApproved)
            };
        }
        public void Add(AddModel<KeywordLanguageLine> model)
        {
            var validator = new AddValidator(model);
            var keywordLanguageLine = model.Item;
            var validationResults = validator.Validate();
            if (!validator.IsValid)
            {
                throw new ValidationException(Resources.InvalidEntityMessage)
                {
                    ValidationResult = validationResults
                };
            }
            var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;


            var keyword = new Keyword
            {
                CreateDate = DateTime.Now,
                CreatedBy = fikriKibarIdentity.UserId,
                UpdatedBy = fikriKibarIdentity.UserId,
                UpdateDate = DateTime.Now

            };

            var addedKeyword = _keywordDal.Add(keyword);

            foreach (var languageId in model.SelectedLanguageIds)
            {
                keywordLanguageLine.KeywordId = addedKeyword.Id;
                keywordLanguageLine.Keyword = null;
                keywordLanguageLine.LanguageId = languageId;
                keywordLanguageLine.KeywordName = model.Item.KeywordName;
                keywordLanguageLine.KeywordDescription = model.Item.KeywordDescription;
                keywordLanguageLine.CreatedBy = fikriKibarIdentity.UserId;
                keywordLanguageLine.CreateDate = DateTime.Now;
                keywordLanguageLine.UpdatedBy = fikriKibarIdentity.UserId;
                keywordLanguageLine.UpdateDate = DateTime.Now;
                keywordLanguageLine.DisplayOrder = addedKeyword.Id;
                keywordLanguageLine.IsApproved = model.Item.IsApproved;
                _keywordLanguageLineDal.Add(keywordLanguageLine);
            }
        }
        public UpdateModel<KeywordLanguageLine> Update(int id, string language)
        {
            var keywordLanguageLine = _keywordLanguageLineDal.Filter(e => e.KeywordId == id && e.Language.LanguageCode == language).FirstOrDefault();
            if (keywordLanguageLine == null) throw new NotFoundException();
            return new UpdateModel<KeywordLanguageLine>
            {
                LanguageList = _languageDal.Filter(e => e.IsApproved),
                SelectedLanguageCode = language,
                ItemId = id,
                Item = keywordLanguageLine
            };
        }
        public void Update(UpdateModel<KeywordLanguageLine> model)
        {
            var validator = new UpdateValidator(model);
            var validationResults = validator.Validate();
            if (!validator.IsValid)
            {
                throw new ValidationException(Resources.InvalidEntityMessage)
                {
                    ValidationResult = validationResults
                };
            }
            var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;

            var keyword = _keywordDal.GetById(model.ItemId);

            var keywordHistory = new KeywordHistory
            {
                KeywordId = keyword.Id,
                CreateDate = keyword.CreateDate,
                CreatedBy = keyword.CreatedBy,
                UpdateDate = keyword.UpdateDate,
                UpdatedBy = keyword.UpdatedBy,
                IsDeleted = false
            };
            _keywordHistoryDal.Add(keywordHistory);


            keyword.UpdateDate = DateTime.Now;
            keyword.UpdatedBy = fikriKibarIdentity.UserId;
            var affectedKeyword = _keywordDal.Update(keyword);

            var keywordLanguageLine = _keywordLanguageLineDal.Filter(e => e.KeywordId == model.ItemId && e.Language.LanguageCode == model.SelectedLanguageCode).FirstOrDefault();

            if (keywordLanguageLine == null)
            {
                keywordLanguageLine = new KeywordLanguageLine
                {
                    KeywordId = affectedKeyword.Id,
                    Keyword = null,
                    LanguageId = _languageDal.GetByCode(model.SelectedLanguageCode).Id,
                    KeywordName = model.Item.KeywordName,
                    KeywordDescription = model.Item.KeywordDescription,
                    CreatedBy = fikriKibarIdentity.UserId,
                    CreateDate = DateTime.Now,
                    UpdatedBy = fikriKibarIdentity.UserId,
                    UpdateDate = DateTime.Now,
                    DisplayOrder = affectedKeyword.Id,
                    IsApproved = model.Item.IsApproved
                };
                _keywordLanguageLineDal.Add(keywordLanguageLine);

            }
            else
            {
                var keywordLanguageLineHistory = new KeywordLanguageLineHistory
                {
                    KeywordLanguageLineId = keywordLanguageLine.Id,
                    KeywordId = keywordLanguageLine.KeywordId,
                    LanguageId = keywordLanguageLine.LanguageId,
                    KeywordName = keywordLanguageLine.KeywordName,
                    KeywordDescription = keywordLanguageLine.KeywordDescription,
                    CreateDate = keywordLanguageLine.CreateDate,
                    CreatedBy = keyword.CreatedBy,
                    UpdateDate = keyword.UpdateDate,
                    UpdatedBy = keyword.UpdatedBy,
                    DisplayOrder = keywordLanguageLine.DisplayOrder,
                    IsApproved = keywordLanguageLine.IsApproved,
                    IsDeleted = false
                };
                _keywordLanguageLineHistoryDal.Add(keywordLanguageLineHistory);

                keywordLanguageLine.UpdateDate = DateTime.Now;
                keywordLanguageLine.UpdatedBy = fikriKibarIdentity.UserId;
                keywordLanguageLine.KeywordName = model.Item.KeywordName;
                keywordLanguageLine.KeywordDescription = model.Item.KeywordDescription;
                keywordLanguageLine.IsApproved = model.Item.IsApproved;

                _keywordLanguageLineDal.Update(keywordLanguageLine);
            }




        }
        public ListModel<KeywordLanguageLine> GetList(string searchTerm, string languageCode, int status, int index, int size, string idsForSort, string idsForApprove, string idsForDelete)
        {
            var model = new ListModel<KeywordLanguageLine>
            {
                Paging = new Paging(),
                ItemList = new List<KeywordLanguageLine>(),
                LanguageList = _languageDal.Filter(e => e.IsApproved)
            };

            if (idsForDelete != null)
            {
                var ids = idsForDelete;
                ids = ids.Remove(ids.Length - 1);
                var idArray = ids.Split(',');
                var idList = idArray.Select(id => id.ConvertToInt()).ToList();
                DeleteSelected(idList, languageCode);

            }
            model.IdsForDelete = null;


            if (idsForApprove != null)
            {
                var ids = idsForApprove;
                ids = ids.Remove(ids.Length - 1);
                var idArray = ids.Split(',');
                var idList = idArray.Select(id => id.ConvertToInt()).ToList();
                ApproveSelected(idList, languageCode);
            }

            model.IdsForApprove = null;

            var sortHelper = new SortHelper<KeywordLanguageLine>();
            sortHelper.OrderByDescending(t => t.DisplayOrder);

            model.Paging.CurrentPageSize = size;
            model.Paging.CurrentPage = index;
            model.SelectedStatus = status;

            if (status != -1)
            {
                var blStatus = status.ToString().ConvertToBoolean();
                model.Paging.TotalItemCount = _keywordLanguageLineDal.GetTotalCount(e => e.KeywordName.Contains(searchTerm) && e.Language.LanguageCode == languageCode && e.IsApproved == blStatus);
            }
            else
            {
                model.Paging.TotalItemCount = _keywordLanguageLineDal.GetTotalCount(e => e.KeywordName.Contains(searchTerm) && e.Language.LanguageCode == languageCode);
            }

            var pageSizeListSetting = _settingDal.GetValueByKey("PageSizeList");
            var pageSizeSettingValue = "10,25,50,100";
            if (pageSizeListSetting != null)
            {
                pageSizeSettingValue = pageSizeListSetting;
            }
            var pageSizeList = pageSizeSettingValue.Split(',').Select(t => new KeyValuePair<int, string>(t.ConvertToInt(), t)).ToList();

            pageSizeList.Insert(0, new KeyValuePair<int, string>(-1, "[" + Resources.All + "]"));
            model.Paging.PageSizeList = pageSizeList;


            if (status != -1)
            {
                var blStatus = status.ToString().ConvertToBoolean();
                model.ItemList = model.Paging.CurrentPageSize > 0 ? _keywordLanguageLineDal.Filter(e => e.KeywordName.Contains(searchTerm) && e.Language.LanguageCode == languageCode && e.IsApproved == blStatus, sortHelper, index, size) : _keywordLanguageLineDal.Filter(e => e.KeywordName.Contains(searchTerm) && e.Language.LanguageCode == languageCode && e.IsApproved == blStatus);
            }
            else
            {
                model.ItemList = model.Paging.CurrentPageSize > 0 ? _keywordLanguageLineDal.Filter(e => e.KeywordName.Contains(searchTerm) && e.Language.LanguageCode == languageCode, sortHelper, index, size) : _keywordLanguageLineDal.Filter(e => e.KeywordName.Contains(searchTerm) && e.Language.LanguageCode == languageCode);
            }


            if (idsForSort != null)
            {
                var ids = idsForSort;
                ids = ids.Remove(ids.Length - 1);
                var idArray = ids.Split(',');
                var idList = idArray.Select(id => id.ConvertToInt()).ToList();
                model.ItemList = SaveSort(idList, languageCode);
            }
            model.IdsForSort = null;

            model.Searched = searchTerm;
            model.SelectedLanguageCode = languageCode;

            model.Paging.CurrentPage = index;
            model.Paging.TotalPageCount = (int)Math.Ceiling((float)model.Paging.TotalItemCount / size);
            return model;
        }
        public void Delete(int id, string language)
        {
            var keywordLanguageLine = _keywordLanguageLineDal.Filter(e => e.Language.LanguageCode == language).FirstOrDefault(e => e.Keyword.Id == id);
            if (keywordLanguageLine == null) return;
            var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;
            var keywordLanguageLineHistory = new KeywordLanguageLineHistory
            {
                KeywordLanguageLineId = keywordLanguageLine.Id,
                KeywordId = keywordLanguageLine.KeywordId,
                LanguageId = keywordLanguageLine.LanguageId,
                KeywordName = keywordLanguageLine.KeywordName,
                KeywordDescription = keywordLanguageLine.KeywordDescription,
                CreateDate = keywordLanguageLine.CreateDate,
                CreatedBy = keywordLanguageLine.CreatedBy,
                UpdateDate = DateTime.Now,
                UpdatedBy = fikriKibarIdentity.UserId,
                DisplayOrder = keywordLanguageLine.DisplayOrder,
                IsApproved = keywordLanguageLine.IsApproved,
                IsDeleted = true
            };
            _keywordLanguageLineHistoryDal.Add(keywordLanguageLineHistory);
            _keywordLanguageLineDal.Delete(keywordLanguageLine);

            if (_keywordLanguageLineDal.Filter(e => e.KeywordId == id).Any()) return;
            var keyword = _keywordDal.GetById(id);
            if (keyword == null) return;
            var keywordHistory = new KeywordHistory
            {
                KeywordId = keyword.Id,
                CreateDate = keyword.CreateDate,
                CreatedBy = keyword.CreatedBy,
                UpdateDate = DateTime.Now,
                UpdatedBy = fikriKibarIdentity.UserId,
                IsDeleted = true
            };
            _keywordHistoryDal.Add(keywordHistory);
            _keywordDal.Delete(keyword);
        }

        private List<KeywordLanguageLine> SaveSort(IReadOnlyList<int> idList, string languageCode)
        {
            var returnedValue = new List<KeywordLanguageLine>();
            for (var i = 0; i < idList.Count; i++)
            {
                var keywordLanguageLine = _keywordLanguageLineDal.Filter(e => e.Language.LanguageCode == languageCode).FirstOrDefault(e => e.Keyword.Id == idList[i]);

                if (keywordLanguageLine == null) continue;
                var keyword = _keywordDal.GetById(keywordLanguageLine.Keyword.Id);
                var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;

                var keywordHistory = new KeywordHistory
                {
                    KeywordId = keyword.Id,
                    CreateDate = keyword.CreateDate,
                    CreatedBy = keyword.CreatedBy,
                    UpdateDate = DateTime.Now,
                    UpdatedBy = fikriKibarIdentity.UserId,
                    IsDeleted = false
                };
                _keywordHistoryDal.Add(keywordHistory);


                keyword.UpdatedBy = fikriKibarIdentity.UserId;
                keyword.UpdateDate = DateTime.Now;
                _keywordDal.Update(keyword);

                var keywordLanguageLineHistory = new KeywordLanguageLineHistory
                {
                    KeywordLanguageLineId = keywordLanguageLine.Id,
                    KeywordId = keywordLanguageLine.KeywordId,
                    LanguageId = keywordLanguageLine.LanguageId,
                    KeywordName = keywordLanguageLine.KeywordName,
                    KeywordDescription = keywordLanguageLine.KeywordDescription,
                    CreateDate = keywordLanguageLine.CreateDate,
                    CreatedBy = keywordLanguageLine.CreatedBy,
                    UpdateDate = DateTime.Now,
                    UpdatedBy = fikriKibarIdentity.UserId,
                    DisplayOrder = keywordLanguageLine.DisplayOrder,
                    IsApproved = keywordLanguageLine.IsApproved,
                    IsDeleted = false
                };
                _keywordLanguageLineHistoryDal.Add(keywordLanguageLineHistory);


                keywordLanguageLine.DisplayOrder = i + 1;
                keywordLanguageLine.UpdatedBy = fikriKibarIdentity.UserId;
                keywordLanguageLine.UpdateDate = DateTime.Now;
                keywordLanguageLine.Keyword = keyword;
                _keywordLanguageLineDal.Update(keywordLanguageLine);
                returnedValue.Add(keywordLanguageLine);
            }
            return returnedValue;
        }
        private void ApproveSelected(IEnumerable<int> idList, string languageCode)
        {
            foreach (var id in idList)
            {
                var keywordLanguageLine = _keywordLanguageLineDal.Filter(e => e.Language.LanguageCode == languageCode).FirstOrDefault(e => e.Keyword.Id == id);
                if (keywordLanguageLine == null) continue;
                var keyword = _keywordDal.GetById(keywordLanguageLine.Keyword.Id);
                var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;
                var keywordHistory = new KeywordHistory
                {
                    KeywordId = keyword.Id,
                    CreateDate = keyword.CreateDate,
                    CreatedBy = keyword.CreatedBy,
                    UpdateDate = DateTime.Now,
                    UpdatedBy = fikriKibarIdentity.UserId,
                    IsDeleted = false
                };
                _keywordHistoryDal.Add(keywordHistory);
                keyword.UpdatedBy = fikriKibarIdentity.UserId;
                keyword.UpdateDate = DateTime.Now;
                _keywordDal.Update(keyword);

                var keywordLanguageLineHistory = new KeywordLanguageLineHistory
                {
                    KeywordLanguageLineId = keywordLanguageLine.Id,
                    KeywordId = keywordLanguageLine.KeywordId,
                    LanguageId = keywordLanguageLine.LanguageId,
                    KeywordName = keywordLanguageLine.KeywordName,
                    KeywordDescription = keywordLanguageLine.KeywordDescription,
                    CreateDate = keywordLanguageLine.CreateDate,
                    CreatedBy = keywordLanguageLine.CreatedBy,
                    UpdateDate = DateTime.Now,
                    UpdatedBy = fikriKibarIdentity.UserId,
                    DisplayOrder = keywordLanguageLine.DisplayOrder,
                    IsApproved = keywordLanguageLine.IsApproved,
                    IsDeleted = false
                };
                _keywordLanguageLineHistoryDal.Add(keywordLanguageLineHistory);


                keywordLanguageLine.UpdatedBy = fikriKibarIdentity.UserId;
                keywordLanguageLine.UpdateDate = DateTime.Now;
                keywordLanguageLine.IsApproved = true;
                keywordLanguageLine.Keyword = keyword;
                _keywordLanguageLineDal.Update(keywordLanguageLine);

            }
        }
        private void DeleteSelected(IEnumerable<int> idList, string languageCode)
        {
            foreach (var id in idList)
            {
                Delete(id, languageCode);
            }
        }

        #endregion
    }
}
